/*
 * MinInclusiveValidator.java
 * 
 * Created on 22-Aug-2007, 18:48:33
 * 
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package com.grubby.databean.constraints.validation;

import com.grubby.databean.constraints.annotation.MinInclusive;
import java.lang.annotation.Annotation;

/**
 * A validator for the {@link MinInclusive MinInclusive} constraint.
 * Note that all comparisons are done as doubles. Therefore there will be
 * information loss for values of type long that exceed the precision of double,
 * which may affect the comparison.
 * @see MinInclusive
 *
 * @author Anders Holmgren, with alterations by A. HARMEL-LAW. 
 * E: andrew.harmel.law@gmail.com
 * @version 0.1
 */
public class MinInclusiveValidator extends AbstractConstraintValidator {

    /**
     * Constructs a MinInclusiveValidator object.
     */
    // suppress the unchecked warning for unchecked generic array creation
    @SuppressWarnings("unchecked")
    public MinInclusiveValidator() {
        super(MinInclusive.class);
    }

    public ConstraintViolation validate(Object objValue, Annotation constraint) {
        ensureConstraintIsSupported(constraint);

        MinInclusive mi = (MinInclusive)constraint;
        ConstraintViolation result = null;

        if (objValue == null) {
            result = new ConstraintViolation(mi,
                "MaxInclusive constraint violated. The value provided was null.");
        } else {
            if (!(objValue instanceof Number))
                throw new IllegalArgumentException("MinInclusiveValidator was passed a value that was not a subclass of Number");
            
            /*
             * Convert the number to a double and then compare with the 
             * constraints value.
             * Note the conversion to double may result in the loss of 
             * information for values of type long.
             */
            Number value = (Number)objValue;
            if (!(value.doubleValue() >= mi.value())) {
                result = new ConstraintViolation(mi,
                    "MinInclusive constraint violated. Value " + value + 
                    " is less than min " + mi.value());
            }
        }
        
        return result;
    }    
}